#include "Bitstr.h"


namespace Omvandla
{

	void tal_str( int tal, Bitstr *str, int nrbits )
	{
		/**
		*	The function tal_str in namespace Omvandla.
		*	This functions transforms an integer into a binary string (Bitstr).
		*	It works by checking if the integer is negative, and flaging that if it is.
		*	Then simlpe integerdivision and pushing the rest into the front of the Bitstr.
		*	Depending of wordlength, any spare bits are set to value = '0'
		*	If the negative flag is set, a call to the Bitstr twocomp method is made. 
		*/
		int filledBits = 0;
		bool negative = false;
		if( tal < 0 )
		{
			negative = true;
			tal = -tal;
		}

		while( tal > 1 )
		{
			if( tal % 2 == 0 )
				str->push_front( Bit('0') );
			else
				str->push_front( Bit('1') );
			filledBits++;
			tal = tal / 2;
		}
		if( tal == 1 )
			str->push_front( Bit('1') );
		else
			str->push_front( Bit('0') );
		filledBits++;

		for( int i = filledBits; i < nrbits; i++ )
		{
			str->push_front( Bit('0') );
		}
		if( negative )
			*str = *str->twocomp( nrbits );
	}

	int str_tal( Bitstr str )
	{
		/**
		*	The function str_tal in namespace Omvandla.
		*	Exists to transform from binary string (Bitstr) to a regular integer.
		*	Works by traversing through the Bitstr from end to front and adding Bit value multiplied with 2^(Bitstr positional value).
		*	Lastly the last (first) position of the Bitstr is checked, if it's value = '1' that bit is calculated with negative positional value instead.
		*/

		int bit = 0;
		int sum = 0;
		int wordLength = str.size();
		int dummy;

		while( bit != wordLength - 1 )
		{
			Bit temp = str.back();
			if( temp.GetValue() == '1' )
				dummy = 1;
			else
				dummy = 0;

			sum += ( dummy * pow(2,bit) );
			bit++;

			str.pop_back();
		}

		Bit temp = str.back();
		if( temp.GetValue() == '1' )
			dummy = 1;
		else
			dummy = 0;

		sum += ( dummy * (-(pow(2,bit))) );

		return sum;
	}

} // end namespace Omvandla